import axios from "axios";
import { message } from "ant-design-vue";
import { baseURL } from "@/utils/config";

const request = axios.create({
  baseURL: baseURL,
});

// 请求拦截器
request.interceptors.request.use(
  cfg => {
    cfg.params = {
      ...cfg.params,
      _: new Date().getTime().toString(),
    };
    return cfg;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const resData = response.data || {};
    const status = resData.success ? 200 : Number(resData.code);
    resData.status = status;
    // 如果是文件流格式
    if (response.request.responseType === "blob") {
      return response;
    }

    if (String(status) === "309") {
      // 登录失败
      return Promise.reject(new Error(resData.message));
    }

    // 请求异常
    if (String(status) !== "200") {
      return Promise.reject(new Error(resData.message || ""));
    }

    // 成功
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 通过导出自定的request实例，来实现对axios的类型封装
export default (cfg) => {
  return request(cfg)
    .then((res) => {
      return res.data;
    })
    .catch(err => {
      message.error(err.message);
    });
};
